package com.wxscrmplus.marketing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.wxscrmplus.common.exception.ServiceException;
import com.wxscrmplus.common.utils.StringUtils;
import com.wxscrmplus.common.core.page.TableDataInfo;
import com.wxscrmplus.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wxscrmplus.system.service.ISysOssService;
import com.wxscrmplus.wxcp.factory.WxCpServiceFactory;
import com.wxscrmplus.marketing.domain.MarMsgAttachments;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpMediaService;
import org.springframework.stereotype.Service;
import com.wxscrmplus.marketing.domain.bo.MarMsgAttachmentsBo;
import com.wxscrmplus.marketing.domain.vo.MarMsgAttachmentsVo;
import com.wxscrmplus.marketing.mapper.MarMsgAttachmentsMapper;
import com.wxscrmplus.marketing.service.IMarMsgAttachmentsService;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.UUID;

/**
 * 消息语附件Service业务层处理
 *
 * @author 王永超
 * @date 2023-05-11
 */
@RequiredArgsConstructor
@Service
public class MarMsgAttachmentsServiceImpl extends WxCpServiceFactory implements IMarMsgAttachmentsService {

    private final MarMsgAttachmentsMapper baseMapper;
    private final ISysOssService ossService;

    /**
     * 刷新附件 企微临时素材（3天内刷新一次，注意：媒体文件上传后获取的唯一标识，3天内有效）
     */
    @Override
    public void refreshAttachmentsQwMedia() {
        List<MarMsgAttachments> marMsgAttachmentsList = baseMapper.selectList(Wrappers.query(new MarMsgAttachments()).lambda());
        for (MarMsgAttachments marMsgAttachments : marMsgAttachmentsList) {
            try {
                this.refreshQwMedia(marMsgAttachments);
            } catch (Exception ignored) {
            }
        }
    }

    @Override
    public void refreshQwMedia(MarMsgAttachments msgAttachments) {
        JSONObject attContent = msgAttachments.getAttContent();
        WxCpMediaService mediaService = getMediaService();
        String ossUrl = null;
        if (ObjectUtil.isNotNull(attContent.get("ossId"))) {
            ossUrl = ossService.genOssUrl(Long.parseLong(attContent.get("ossId").toString()), 60 * 60 * 24 * 3);
        }
        try {
            switch (msgAttachments.getMsgtype()) {
                case WxConsts.MediaFileType.IMAGE:
                    if (StrUtil.isNotBlank(ossUrl)) {
                        WxMediaUploadResult upload = mediaService.upload(WxConsts.MediaFileType.IMAGE, UUID.randomUUID().toString(), ossUrl);
                        attContent.set("mediaId", upload.getMediaId());
                    } else {
                        throw new ServiceException("请上传图片");
                    }
                    break;
                case WxConsts.MediaFileType.VIDEO:
                    if (StrUtil.isNotBlank(ossUrl)) {
                        WxMediaUploadResult upload = mediaService.upload(WxConsts.MediaFileType.VIDEO, UUID.randomUUID().toString(), ossUrl);
                        attContent.set("mediaId", upload.getMediaId());
                    } else {
                        throw new ServiceException("请上传视频");
                    }
                    break;
                case WxConsts.MediaFileType.FILE:
                    if (StrUtil.isNotBlank(ossUrl)) {
                        WxMediaUploadResult upload = mediaService.upload(WxConsts.MediaFileType.FILE, UUID.randomUUID().toString(), ossUrl);
                        attContent.set("mediaId", upload.getMediaId());
                    } else {
                        throw new ServiceException("请上传文件");
                    }
                    break;
                case "link":
                    if (StrUtil.isBlank(attContent.getStr("title")) ||
                        StrUtil.isBlank(attContent.getStr("url"))) {
                        throw new ServiceException("标题或链接为空");
                    }
                    if (StrUtil.isNotBlank(ossUrl)) {
                        attContent.set("picurl", ossUrl);
                    }
                    break;
            }
        } catch (WxErrorException | IOException e) {
            throw new RuntimeException(e.getMessage());
        }
        baseMapper.updateById(msgAttachments);
    }

    /**
     * 查询消息语附件
     */
    @Override
    public MarMsgAttachmentsVo queryById(Long batchSendMsgAttId) {
        return baseMapper.selectVoById(batchSendMsgAttId);
    }

    /**
     * 查询消息语附件列表
     */
    @Override
    public TableDataInfo<MarMsgAttachmentsVo> queryPageList(MarMsgAttachmentsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MarMsgAttachments> lqw = buildQueryWrapper(bo);
        Page<MarMsgAttachmentsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询消息语附件列表
     */
    @Override
    public List<MarMsgAttachmentsVo> queryList(MarMsgAttachmentsBo bo) {
        LambdaQueryWrapper<MarMsgAttachments> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MarMsgAttachments> buildQueryWrapper(MarMsgAttachmentsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MarMsgAttachments> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getMsgtype()), MarMsgAttachments::getMsgtype, bo.getMsgtype());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getTargetType()), MarMsgAttachments::getTargetType, bo.getTargetType());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getTargetId()), MarMsgAttachments::getTargetId, bo.getTargetId());
        return lqw;
    }

    /**
     * 新增消息语附件
     */
    @Override
    public Boolean insertByBo(MarMsgAttachmentsBo bo) {
        MarMsgAttachments add = BeanUtil.toBean(bo, MarMsgAttachments.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setMsgAttId(add.getMsgAttId());
        }
        this.refreshQwMedia(add);
        return flag;
    }

    /**
     * 修改消息语附件
// df253826d6b3f98bc300d4886a94cabe
     */
    @Override
    public Boolean updateByBo(MarMsgAttachmentsBo bo) {
        MarMsgAttachments update = BeanUtil.toBean(bo, MarMsgAttachments.class);
        validEntityBeforeSave(update);
        this.refreshQwMedia(update);
        return true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MarMsgAttachments entity) {
        Long count = baseMapper.selectCount(Wrappers.query(new MarMsgAttachments())
            .lambda().eq(MarMsgAttachments::getTargetType, entity.getTargetType())
            .eq(MarMsgAttachments::getTargetId, entity.getTargetId()));
        if (count >= 9) {
            throw new ServiceException("最多支持添加9个附件");
        }
    }

    /**
     * 批量删除消息语附件
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
